import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '../mconfig';
import { UpdateContractService, queryContractMaterialList } from '../services';
import { contractTableConfig } from '../mconfig';
import { Col, Row, message } from 'antd';
import { getColorTextLoadMap, getKeyRouter, getLoadMapList, getSelectDataMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { OpenMaterialType } from './OpenMaterialType';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ILoadMapTypeAll } from '@/common';
import { AssetAcquisitionManageAPI } from '../common/type';

export const ContractModal: React.FC<AssetAcquisitionManageAPI.IOpenMaterialModal> = ({ onClose, isShowModal }) => {
  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);
  const styleFixCls = 'contract-styfixcls-';
  // /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);
  // /** 资产类型 */
  const assetTypeList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);

  /** 获取上下文 */
  const {
    contractForm,
    materielList,
    contractMaterList,
    addMatrielList,
    contractList,
    purchaseList,
    curRes,
    rightTableProps: { materielForm },
    acquisitionDispatch,
  } = useContext(AcquisitionManageContext);

  // 查询合同列表 入参
  const contractParams = {
    // applyID: purchaseList[0].applyID,
  };

  /** 获取列表 */
  const { data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = UpdateContractService(curRes, contractParams);
  /**
   *  获取左侧类型数据
   */

  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<any>([]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    setCheckMaterialList(selectInfo);
  };

  /** 初始化 */
  useEffect(() => {
    setCheckMaterialList(contractList);
  }, [isShowModal]);

  // 获取选择合同下得 物料列表
  const { queryContractRun, queryContractLoading } = queryContractMaterialList();

  /** 点击确定 */
  const onSave = () => {
    if (checkMaterialList && checkMaterialList?.length > 1) {
      return message.error('请选择一个合同!');
    }
    if (checkMaterialList && checkMaterialList?.length > 0) {
      contractForm?.setFieldsValue({
        contractName: checkMaterialList[0]?.contractName,
        contractProcessName: '',
      });

      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_CONTRACT,
        payload: [...checkMaterialList],
      });

      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_CONTRACT_PROCESS,
        payload: [],
      });

      onCloseModalCommon(updateModalRef);

      // queryContractRun({ id: checkMaterialList[0]?.id }).then((res: any) => {
      //   if (res && res?.msgFlag) {
      //     // 选择的合同
      //     acquisitionDispatch({
      //       type: IAcquisitionActionEnum.SELECT_CONTRACT,
      //       payload: [...checkMaterialList],
      //     });
      //     // 合同带出的物料
      //     acquisitionDispatch({
      //       type: IAcquisitionActionEnum.SELECT_CONTRACT_MATRIEL,
      //       payload: res?.rows,
      //     });
      //     // 更新物料列表
      //     acquisitionDispatch({
      //       type: IAcquisitionActionEnum.SELECT_MATERIEL,
      //       payload: addMatrielList.concat(res?.rows),
      //     });
      //     onCloseModalCommon(updateModalRef);
      //   }
      // });
    } else {
      message.error('请至少选择一个合同');
    }
    return;
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'合同列表'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.65}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: 10,
        }}
        onOk={onSave}
      >
        <UpdateTableCommon
          styleFixCls={styleFixCls}
          searchProps={{
            searchList,
            onReset,
            onSearch,
          }}
          selectTablePorps={{
            onSelectTable,
            selectRowObjList: checkMaterialList,
            selectType: 'radio',
            setCheckRows: setCheckMaterialList,
          }}
          tableProps={{
            columns: contractTableConfig(),
            loading,
            dataSource: data?.rows,
            pagination,
            onPageChange,
            rowKey: 'id',
            tableTotalShow: (total: any, range: any) => {
              return (
                <div
                  style={{
                    display: 'flex',
                    width: '100%',
                    justifyContent: 'space-between',
                  }}
                >
                  <div>
                    已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条合同
                  </div>
                  <div>{showTotalInfo(total, range)}</div>
                </div>
              );
            },
          }}
        />
      </OneModal>
    </>
  );
};
